﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using CSEngine;

namespace Server
{
    class LocalGameData : GameData
    {
        private Game game;
        private Thread gameThread;

        public LocalGameData(NetworkStream str)
            : base(GameType.LOCAL, str)
        {
            game = null;
            gameThread = null;
        }

        public LocalGameData(NetworkStream str, AI myAI)
            : base(GameType.LOCAL, str, myAI)
        {
            game = null;
            gameThread = null;
        }

        public void StartGame()
        {
            game = new Game(Settings.Rows,Settings.Cols);
            gameThread = new Thread(new ThreadStart(game.Play));
            game.BindPlayer1Turn(WaitForRemoteMove);
            game.BindPlayer2Turn(AI.GetNextMove);
            //game.BoardUpdated += DisplayBoard;        // Display every move
            game.BoardUpdated += DisplayEveryOther;
            game.GameOver += NotifyGameOver;
            game.GameOver += Reset;
            game.IllegalMove += NotifyIllegal;
            in_progress = true;
            gameThread.Start();
        }

        private void Reset(object sender, GameOverArgs e)
        {
            game = null;
            in_progress = false;
        }

        public override AI AI
        {
            get { return ai; }
            set
            {
                ai = value;
                game.BindPlayer2Turn(ai.GetNextMove);
            }
        }

        /// <summary>
        /// Acquire the Game instance being managed by this instance
        /// </summary>
        /// <exception cref="System.InvalidOperationException">Thrown when
        /// there is not currently a game being managed by this instance</exception>
        public Game GetGame()
        {
            if (in_progress)
                return game;
            else
                throw new InvalidOperationException("No Game Currently In Progress");
        }
    };
}
